import { Form, Input, Button, message } from 'antd'
import { ImportantEditModal } from '@/desktop/components'
import services from '@/services'
import type { GroupExtra } from '@/services/contact-types/groups'

export type GroupEditInfo = GroupExtra & { remark: string }

export default function EditInfo(props: { editing: GroupEditInfo | null; onFinish: () => void }) {
  const { editing, onFinish } = props

  return <ImportantEditModal
    title="编辑群资料"
    width="650px"
    open={editing !== null}
    onCancel={onFinish}
  >
    {editing !== null ? <Content initial={editing} onFinish={onFinish} /> : null}
  </ImportantEditModal>
}

function Content(props: { initial: GroupEditInfo; onFinish: () => void }) {
  const { initial, onFinish } = props

  const submit = useCallback(
    async (values: GroupEditInfo) => {
      const res = await services.groups.update(values)
      if (res.success) {
        void message.success('保存成功！')
        onFinish()
      } else {
        void message.error(`保存失败：${res.error}`)
      }
    },
    [onFinish],
  )

  return <Form initialValues={initial} labelCol={{ span: 3 }} onFinish={submit}>
    <main>
      <Form.Item name="remark" label="群备注">
        <Input maxLength={25} />
      </Form.Item>

      <Form.Item name="describe" label="群描述">
        <Input.TextArea rows={5} maxLength={255} showCount />
      </Form.Item>
    </main>
    <footer>
      <Button onClick={onFinish}>取消</Button>
      <Button type="primary" htmlType="submit">
        保存
      </Button>
    </footer>
  </Form>
}
